import { Component, ViewChild, ElementRef, Renderer } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validator, Validators } from '@angular/forms';
import { AuthService } from 'service/AuthService';
import { ApiRequest } from 'service/ApiRequest';
// import { xml } from '../../activexobject';

@Component({
  selector: 'personal-data',
  templateUrl: './PersonalData.html',
})

export class PersonalDataComponent {

  @ViewChild('file')
  inputFile: ElementRef;

  @ViewChild('pic')
  pic: ElementRef;

  //表单数据模型
  private formModel: FormGroup;

  userInfo:any = null;

  constructor(
    private formBuilder: FormBuilder,
    private renderer: Renderer,
    private authService: AuthService,
    private apiRequest:ApiRequest
    // private activexobject: xml
  ) {
    this.userInfo = this.authService.getUserInfo();
  }

  ngOnInit() {
    this.formModel = this.formBuilder.group({
      file: [null],
      NickName: [this.userInfo ? this.userInfo.NickName : '', Validators.compose([Validators.required])],
      Gender: [this.userInfo ? (this.userInfo.Gender || 1) : 1, Validators.compose([Validators.required])],
      Abstract: [this.userInfo ? this.userInfo.Abstract : ''],
    });
  }

  ngAfterViewInit() {
    // console.log(this.inputFile)
  }

  onChange() {
    try {
      let file = this.inputFile.nativeElement.files[0];
      let reader = new FileReader();
      let _this = this;
      reader.readAsDataURL(file);
      reader.addEventListener('load', function () {
        _this.pic.nativeElement.src = reader.result;
        // 请求更新头像
        _this.apiRequest.updateAvatar(reader.result);
      });
    } catch (e) {
      this.inputFile.nativeElement.select();
      this.inputFile.nativeElement.blur();
      let path = this.inputFile.nativeElement.value;
      this.pic.nativeElement.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src=\"" +
        path + "\")";
      //如何获取到图片文件？
    }
  }

  onSubmit() {
    // console.log(this.formModel.valid);
    // console.log(this.formModel.get('pic'));
    // console.log(this.formModel.get('nickname').valid);
    if (this.formModel.valid) {
      const userInfo = Object.assign(this.userInfo, this.formModel.value);
      this.apiRequest.updateUserProfile(userInfo);
    }
  }
}
